#!/bin/bash

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
# shellcheck source=scripts/utils.sh
. "${PROJECT_DIR}/scripts/utils.sh"

action=${1-}
target=${2-}
args=("$@")

function check_config_file() {
  if [[ ! -f "${CONFIG_FILE}" ]]; then
    echo "Configuration file not found: ${CONFIG_FILE}"
    return 3
  fi
  if [[ -f .env ]]; then
    ls -l .env | grep "${CONFIG_FILE}" &>/dev/null
    code="$?"
    if [[ "$code" != "0" ]]; then
      echo ".env There is a problem with the soft connection, Please update it again"
      rm -f .env
    fi
  fi

  if [[ ! -f .env ]]; then
    ln -s "${CONFIG_FILE}" .env
  fi
}

function pre_check() {
  check_config_file || return 3
}

function usage() {
  echo "Bees Deployment Management Script"
  echo
  echo "Usage: "
  echo "  ./beesctl.sh [COMMAND] [ARGS...]"
  echo "  ./beesctl.sh --help"
  echo
  echo "Installation Commands: "
  echo "  install           Install Bees"
  echo
  echo "Management Commands: "
  echo "  start             Start   Bees"
  echo "  stop              Stop    Bees"
  echo "  restart           Restart Bees"
  echo "  status            Check   Bees"
  echo "  down              Offline Bees"
  echo
}

EXE=""

function restart() {
  stop
  echo -e "\n"
  start
}

function get_docker_compose_cmd_line {
  cmd="docker-compose -f ./compose/docker-compose-network.yml"
  cmd="${cmd} -f ./compose/docker-compose-mysql.yml"
  cmd="${cmd} -f ./compose/docker-compose-redis.yml"
  cmd="${cmd} -f ./compose/docker-compose-core.yml"
  cmd="${cmd} -f ./compose/docker-compose-task.yml"
  cmd="${cmd} -f ./compose/docker-compose-nginx.yml"
  echo $cmd
}

function main() {
  if [[ "${action}" == "help" || "${action}" == "h" || "${action}" == "-h" || "${action}" == "--help" ]]; then
    echo ""
  else
    pre_check || return 3
    EXE=$(get_docker_compose_cmd_line)
  fi
  case "${action}" in
  install)
    bash "${SCRIPT_DIR}/install.sh"
    ;;
  start)
    ${EXE} up -d
    ;;
  restart)
    restart
    ;;
  stop)
    ${EXE} stop
    ;;
  status)
    ${EXE} ps
    ;;
  down)
    ${EXE} down
    ;;
  --help)
    usage
    ;;
  -h)
    usage
    ;;
  *)
    echo "No such command: ${action}"
    usage
    ;;
  esac
}

main "$@"

